/*
 * @Author: wangjq4214
 * @Date: 2022-05-06 22:21:05
 * @LastEditTime: 2022-05-06 23:07:28
 * @LastEditors: wangjq4214
 */
import { get as getReq } from '@/apis';
import {
  NodeStatusRes,
  NODE_STATUS,
  NodeStatusResData,
  STORAGE_STATUS,
  StorageStatusRes,
} from '@/apis/dashboard';

const rawNodeDataAtom = atom<{
  loading: boolean;
  error: null | unknown;
  data: null | NodeStatusResData[];
}>({ data: null, error: null, loading: false });

export const nodeDataAtom = atom(
  (get) => get(rawNodeDataAtom),
  (get, set) => {
    const fetcher = async () => {
      set(rawNodeDataAtom, (prev) => ({ ...prev, loading: true }));

      try {
        const data = await getReq<NodeStatusRes>(NODE_STATUS);

        set(rawNodeDataAtom, { loading: false, error: null, data: data.data });
      } catch (error) {
        set(rawNodeDataAtom, { loading: false, error, data: null });
      }
    };

    fetcher();
  }
);

export const nodeBarDataAtom = atom((get) => {
  const tmp = get(rawNodeDataAtom);

  return tmp.data?.map((item) => {
    return { name: item.item, count: item.count };
  });
});

const rawStorageDataAtom = atom<{
  loading: boolean;
  error: null | unknown;
  data: null | StorageStatusRes;
}>({ data: null, error: null, loading: false });

export const storageDataAtom = atom(
  (get) => get(rawStorageDataAtom),
  (get, set) => {
    const fetcher = async () => {
      set(rawStorageDataAtom, (prev) => ({ ...prev, loading: true }));

      try {
        const data = await getReq<StorageStatusRes>(STORAGE_STATUS);

        set(rawStorageDataAtom, {
          loading: false,
          error: null,
          data: data,
        });
      } catch (error) {
        set(rawStorageDataAtom, { loading: false, error, data: null });
      }
    };

    fetcher();
  }
);

export const storagePieAtom = atom((get) => {
  const tmp = get(rawStorageDataAtom);
  const typeMatch: Record<number, string> = {
    1: 'HDFS',
    2: 'HBase',
    3: 'MySQL',
  };

  const sum = tmp.data?.sum.total || 1;

  return tmp.data?.items.map((item) => {
    return {
      name: typeMatch[item.item],
      value: item.count,
      percent: item.count / sum,
    };
  });
});

export const overviewDataAtom = atom((get) => {
  const tmp = get(rawStorageDataAtom);
  const tmpNode = get(rawNodeDataAtom);

  return {
    total: tmp.data?.sum.total,
    today: tmp.data?.sum.today,
    node: tmpNode.data?.length,
  };
});
